package cn.yi.fast.mq.rocketmq.factorybean;

import com.google.common.base.Joiner;
import com.google.common.base.Splitter;
import org.springframework.beans.factory.FactoryBean;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.StringUtils;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class DefaultSubscribeMapFactoryBean implements FactoryBean<Map<String, String>>, InitializingBean {

    @Value("${mq.topic2TagMapping}")
    private String topic2TagMapping;

    private Map<String, String> subscribeMap;

    @Override
    public Map<String, String> getObject() throws Exception {
        return subscribeMap;
    }

    @Override
    public Class<?> getObjectType() {
        return Map.class;
    }

    @Override
    public boolean isSingleton() {
        return true;
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        subscribeMap = new HashMap<>();//topic1,tag1||tag2;topic2,tag3||tag4
        List<String> topic2TagList = Splitter.on(";").splitToList(topic2TagMapping);
        topic2TagList.forEach(topic2Tag -> {
            String[] topic2Tags = topic2Tag.split(",");
            if (topic2Tags.length != 2) {
                throw new RuntimeException("topic与tag数量不匹配");
            }
            String topic = topic2Tags[0];
            String tags = topic2Tags[1];
            String tagInfos = Joiner.on(" || ").join(Splitter.on(",").splitToList(tags));
            subscribeMap.put(topic, tagInfos);
        });
    }
}
